package com.google.code.p.odbcconnectionchecker.db;

import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Date;

import com.google.code.p.odbcconnectionchecker.ConnectionCheckerMenuItemJdbc;
import com.google.code.p.odbcconnectionchecker.ConnectionMenu;

public class ConnectionCheckerDbTalker {
		
	/**
	 * Check the status of the JDBC connection
	 * @param co A ConnectionCheckerMenuItemJdbc containing details for connecting to the database
	 * @return A ConnectionStatus containing the status of the connection
	 */
	public static ConnectionStatus getConnectionStatus(ConnectionCheckerMenuItemJdbc co) { 
		ConnectionStatus cs = checkConnection(co);
		return cs;
	}
	
	/*
	 * Set the ConnectionStatus object based on the status of the connection
	 */
	private static ConnectionStatus checkConnection(ConnectionCheckerMenuItemJdbc co) {
		ConnectionStatus cs = new ConnectionStatus();
		
		cs.setConnectionActive(false);

		String timestamp = new Timestamp(new Date().getTime()).toString();
		cs.setConnectionTimestamp(timestamp);
	
		try {
			getConnection(co).close();
			cs.setConnectionActive(true);
			cs.setErrorMessage("");
		} catch (MalformedURLException e) {
			cs.setErrorMessage("The URL to the JDBC may not be correct. Please check the connection's configuration.");
			e.printStackTrace();
		} catch (InstantiationException e) {
			cs.setErrorMessage("JDBC Driver could not be instantiated.");
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			cs.setErrorMessage("JDBC Driver could not be instantiated.");
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			cs.setErrorMessage("The Class could not be found. Please check the connection's configuration.");
			e.printStackTrace();
		} catch (SQLException e) {
			cs.setErrorMessage(e.getMessage());
			e.printStackTrace();
		}
		return cs;
	}
	
	private static Connection getConnection(ConnectionCheckerMenuItemJdbc co) throws 
		MalformedURLException, InstantiationException, IllegalAccessException
		, ClassNotFoundException, SQLException {
		if (co.isUseDriver()) { //Driver has to be loaded 
			URL u = new URL("jar:file:" + co.getDriverURL() +"!/");
			URLClassLoader ucl = new URLClassLoader(new URL[] { u });
			Driver d=(Driver)Class.forName(co.getConnectionDriver(), true, ucl).newInstance();;
			DriverManager.registerDriver(new DriverShim(d));
		} else { 
			Class.forName(co.getConnectionDriver());
		}
		Connection cnn = DriverManager.getConnection(co.getConnectionURL(),co.getUsername(),co.getPassword());
		return cnn;
	}
}
